package com.gupaoedu.vip.delegate.dispatcherdelegate;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class DispatcherServlet extends HttpServlet {

    private List<Handler> handlerMapping = new ArrayList<Handler>();

    @Override
    public void init() throws ServletException {
        try {
            Class<?> controllerClazz = Controller.class;
            Handler h = new Handler();
            h.setController(controllerClazz);
            h.setMethod(controllerClazz.getMethod("index",new Class []{String.class}));
            h.setUrl("index");
            handlerMapping.add(h);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        Handler handler = null;
        for (Handler h:handlerMapping) {
            if(h.getUrl().equals(uri)){
                handler = h;
                break;
            }
        }
        try {
            Object o = handler.getMethod().invoke(handler.getController(),req.getParameter("id"));
            resp.getWriter().write(o.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class Handler {
        private Object controller;
        private Method method;
        private String url;

        public Object getController() {
            return controller;
        }

        public void setController(Object controller) {
            this.controller = controller;
        }

        public Method getMethod() {
            return method;
        }

        public void setMethod(Method method) {
            this.method = method;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}
